import { useState } from 'react';
import { useChatStore } from '../../store/chat';
import { useSettingsStore } from '../../store/settings';
import { SidecarClient } from '../../api/sidecar';
import { MessageList } from './MessageList';
import { InputBox } from './InputBox';
import { SubAgentSelector, type SubAgent } from './SubAgentSelector';

export function ChatInterface() {
  const { messages, addMessage, isLoading, setLoading } = useChatStore();
  const { sidecarUrl, agentConfig } = useSettingsStore();
  const [client] = useState(() => new SidecarClient(sidecarUrl));
  const [selectedSubAgent, setSelectedSubAgent] = useState<SubAgent | null>(null);

  const handleSend = async (message: string, attachments?: File[]) => {
    if (!message.trim()) return;

    // Add user message
    addMessage({
      role: 'user',
      content: message,
      attachments: attachments?.map((file) => ({
        id: crypto.randomUUID(),
        name: file.name,
        type: file.type.startsWith('image/') ? 'image' : 'file',
        url: URL.createObjectURL(file),
        size: file.size,
      })),
    });

    setLoading(true);

    try {
      // Stream response from sidecar
      let assistantMessage = '';
      let messageId: string | null = null;

      // Build query options
      const queryOptions: any = {
        model: agentConfig.model,
        systemPrompt: agentConfig.systemPrompt,
        maxTurns: agentConfig.maxTurns,
        includePartialMessages: true,
      };

      // If a sub-agent is selected, add it to the options
      if (selectedSubAgent) {
        queryOptions.subAgentId = selectedSubAgent.id;
      }

      for await (const response of client.queryStream({
        prompt: message,
        options: queryOptions,
      })) {
        // Handle streaming events with delta text
        if (response.type === 'stream_event' && response.event?.delta?.text) {
          assistantMessage += response.event.delta.text;

          // Update or create assistant message
          if (!messageId) {
            messageId = crypto.randomUUID();
            addMessage({
              role: 'assistant',
              content: assistantMessage,
            });
          } else {
            // Update existing message
            useChatStore.setState((state) => ({
              messages: state.messages.map((msg) =>
                msg.id === messageId
                  ? { ...msg, content: assistantMessage }
                  : msg
              ),
            }));
          }
        }
        // Handle final result
        else if (response.type === 'result' && response.result) {
          assistantMessage = response.result;

          if (messageId) {
            // Update with final result
            useChatStore.setState((state) => ({
              messages: state.messages.map((msg) =>
                msg.id === messageId
                  ? { ...msg, content: assistantMessage }
                  : msg
              ),
            }));
          } else {
            // Create message with final result
            addMessage({
              role: 'assistant',
              content: assistantMessage,
            });
          }
        }
      }
    } catch (error) {
      console.error('Error querying agent:', error);
      addMessage({
        role: 'assistant',
        content: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex h-screen flex-col">
      <div className="border-b bg-background p-4">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-xl font-bold">CAgent</h1>
            <p className="text-sm text-muted-foreground">
              AI Agent Platform powered by Claude
            </p>
          </div>
          <SubAgentSelector
            selectedSubAgent={selectedSubAgent}
            onSelect={setSelectedSubAgent}
            disabled={isLoading}
          />
        </div>
      </div>
      <MessageList messages={messages} />
      <InputBox onSend={handleSend} disabled={isLoading} />
    </div>
  );
}

